package com.example.liu_zi_qi

import android.annotation.TargetApi
import android.content.Context
import android.graphics.*
import android.os.Build
import android.os.Message
import android.util.Range
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast

class GameUI constructor(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
    private lateinit var thread: Thread // 绘图线程
    private lateinit var chessBoard: ChessBoard // 棋盘实例
    private var isChessable = true // 标记是否可下子
    var whoWin: ChessManType? = null // 哪方获胜, null代表没有胜利者
    var isExit = false // 标记是否退出游戏
    private lateinit var background: Bitmap // 背景图片

    init {
        this.setZOrderOnTop(true)
        background = BitmapFactory.decodeResource(context.resources, R.drawable.background2)
        this.holder.setFormat(PixelFormat.TRANSLUCENT)
        this.holder.addCallback(this)
        Map.list.removeAll(Map.list)
        Map.history.removeAll(Map.history)
        for (i in 0..3) {
            val arr = Array(4) { 0 }
            for (j in 0..3) {
                if (i == 0 || (i == 1 && (j == 0 || j == 3))) {
                    arr[j] = 2
                }
                if (i == 3 || (i == 2 && (j == 0 || j == 3))) {
                    arr[j] = 1
                }
            }
            Map.map[i] = arr
            Toast.makeText(context, "游戏初始化完成", Toast.LENGTH_SHORT).show()
        }
    }

    override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
        // Implementation here
    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {
        thread.join()
    }

    override fun surfaceCreated(p0: SurfaceHolder) {
        thread = Thread(GameThread(p0))
        thread.start()
    }

    inner class GameThread(val holder: SurfaceHolder?) : Runnable {
        override fun run() {
            while (true) {
                if (isExit) {
                    return
                }
                val canvas = holder?.lockCanvas()
                canvas?.drawBitmap(
                    background, Rect(0, 0, background.width, background.height),
                    Rect(0, 0, canvas.width, canvas.height), Paint()
                )
                canvas?.let {
                    chessBoard = ChessBoard(it)
                    chessBoard.update()
                }
                holder?.unlockCanvasAndPost(canvas)
                if (whoWin != null) {
                    val msg = Message.obtain()
                    msg.what = 1
                    msg.obj = whoWin
                    (context as GameActivity).handle.sendMessage(msg)
                    return
                }
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        val x = event?.x
        val y = event?.y
        if (x != null && y != null) {
            selectChessMan(x, y)
        }
        return true
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun selectChessMan(x: Float, y: Float) {
        val ij = chessBoard.xy2ij(Pair(x, y))
        val i = ij?.first
        val j = ij?.second
        synchronized(Map) {
            isChessable = when (Map.whoChess) {
                ChessManType.WHITE -> Map.map[i!!][j!!] != 2
                else -> Map.map[i!!][j!!] != 1
            }
            if (isChessable) {
                Map.list.forEach {
                    if (x in Range(it.cx - 100, it.cx + 100) && y in Range(it.cy - 100, it.cy + 100)) {
                        Map.list.filter { it.isSelect }.forEach { it.isSelect = false }
                        it.isSelect = true
                    }
                }
                moveChessMan(i!!, j!!)
            }
        }
    }

    private fun moveChessMan(i: Int, j: Int) {
        if (Map.map[i][j] != 0) {
            return
        }
        Map.list.filter { it.isSelect }.forEach {
            if (it.move(i, j)) {
                it.isSelect = false
                Map.whoChess = when (Map.whoChess) {
                    ChessManType.WHITE -> ChessManType.BLACK
                    else -> ChessManType.WHITE
                }
                it.check()
                val msg = Message.obtain()
                msg.what = 2
                val map = HashMap<String, String>()
                map["blackCount"] = Map.list.filter { it.type == ChessManType.BLACK }.size.toString()
                map["whiteCount"] = Map.list.filter { it.type == ChessManType.WHITE }.size.toString()
                msg.obj = map
                (context as GameActivity).handle.sendMessage(msg)
                checkWin()
            }
        }
        (context as GameActivity).checkDraw()
    }

    fun checkWin() {
        if (Map.list.filter { it.type == ChessManType.WHITE }.isEmpty()) {
            whoWin = ChessManType.BLACK
        }
        if (Map.list.filter { it.type == ChessManType.BLACK }.isEmpty()) {
            whoWin = ChessManType.WHITE
        }
    }

    fun exit() {
        isExit = true
        Map.whoChess = ChessManType.WHITE
        thread.join()
    }
}